using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model.Core.DbContexts;
using Model.Core.Entity;
using Model.Core.Entity.Jwts;
using RobotWebApiService.Models;
using Swashbuckle.AspNetCore.Annotations;

namespace RobotWebApiService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PermissionController : ControllerBase
    {
        private readonly MyDbContext _context;

        public PermissionController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取权限树
        /// </summary>
        [HttpGet("tree")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<List<Permission>>))]
        public async Task<ApiResponse<List<Permission>>> GetPermissionTree()
        {
            try
            {
                var permissions = await _context.Permission
                    //.Where(p => p.Code == null)
                    //.Include(p => p.Children)
                    .ToListAsync();
                return new ApiResponse<List<Permission>>(true, "", permissions);
            }
            catch (Exception ex)
            {
                return new ApiResponse<List<Permission>>(false, ex.Message);
            }
        }

        /// <summary>
        /// 分配权限给角色
        /// </summary>
        [HttpPost("assign-role")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<string>))]
        [SwaggerResponse(404, Type = typeof(ApiResponse<string>))]
        public async Task<ApiResponse<string>> AssignPermissionsToRole(
            [FromBody] RolePermissionRequest request)
        {
            try
            {
                var role = await _context.Role.FindAsync(request.RoleId);
                if (role == null) return new ApiResponse<string>(false, "角色不存在");

                var existingPermissions = await _context.RolePermission
                    .Where(rp => rp.RoleId == request.RoleId)
                    .ToListAsync();
                _context.RolePermission.RemoveRange(existingPermissions);

                foreach (var permissionId in request.PermissionIds)
                {
                    _context.RolePermission.Add(new RolePermission 
                    { 
                        RoleId = request.RoleId, 
                        PermissionId = permissionId 
                    });
                }
                await _context.SaveChangesAsync();
                return new ApiResponse<string>(true, "权限分配成功");
            }
            catch (Exception ex)
            {
                return new ApiResponse<string>(false, ex.Message);
            }
        }

        /// <summary>
        /// 获取角色权限
        /// </summary>
        [HttpGet("role/{roleId}")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<List<Guid>>))]
        public async Task<ApiResponse<List<Guid>>> GetRolePermissions(Guid roleId)
        {
            try
            {
                var permissions = await _context.RolePermission
                    .Where(rp => rp.RoleId == roleId)
                    .Select(rp => rp.PermissionId)
                    .ToListAsync();
                return new ApiResponse<List<Guid>>(true, "", permissions);
            }
            catch (Exception ex)
            {
                return new ApiResponse<List<Guid>>(false, ex.Message);
            }
        }
    }

    public class RolePermissionRequest
    {
        public Guid RoleId { get; set; }
        public List<Guid> PermissionIds { get; set; }
    }
}